package com.scalar.chiptrack.engineering.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;
import org.apache.poi.ss.usermodel.Workbook;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.ExcelUtils;
import com.scalar.chiptrack.engineering.forms.EngineeringReportsForm;
import com.scalar.chiptrack.engineering.dao.EngineeringDAO;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.process.dao.PartNumber;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.FinishedGoods;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.operations.vendor.Vendor;
import com.scalar.chiptrack.operations.reports.DataDumpReportsHelper;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class EngineeringReportAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/engineeringReport.do";

    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {

        ActionForward actionForward = null;
        String action = request.getParameter( "action" );
        HttpSession session = request.getSession();

        EngineeringReportsForm reportForm = ( EngineeringReportsForm ) form;

        HashMap<String,String> info = new HashMap<String,String>();
        HashMap<String,String> errors = new HashMap<String,String>();

        Workbook workbook = null;
        String fileName = "";

        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );

        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        if( ( action == null ) || ( action.trim().length() == 0 ) )
        {
            actionForward = null;
        }
        else
        {
            action = action.trim();
        }

        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME + "?" + request.getQueryString() );
            return ( mapping.findForward ( "login" ) );
        }

        ArrayList<FinishedGoods> partNumberList = null;
        ArrayList mktgPartNumberSelectList = null;
        String psType = null;

        if( "yield".equalsIgnoreCase( action ) )
        {               
            try
            {
                if( ( reportForm.getProcessStep() == null ) || "0".equalsIgnoreCase(reportForm.getProcessStep() ) )
                {
                    request.setAttribute( "partNumberList", new ArrayList() );
                    request.setAttribute( "locationList",    VendorDAO.getVendorNamesByPsType(null, "ALL") );
                    request.setAttribute("showMessage", "false");
                }
                else
                {
                    if ( "SORTBIN".equalsIgnoreCase( reportForm.getProcessStep() ))
                    {
                        psType = Constants.LOCATION_TYPE_SORT;
                        request.setAttribute("showMessage", "true");
                    }
                    else if ( "FT".equalsIgnoreCase( reportForm.getProcessStep() ))
                    {
                        psType = reportForm.getProcessStep();
                        request.setAttribute("showSoftBinMessage", "true");
                    }
                    else
                    {
                        psType = reportForm.getProcessStep();
                        request.setAttribute("showMessage", "false");
                    }

                    if ( reportForm.getBaseProductId() > 0  )
                    {
                        request.setAttribute( "partNumberList", ProductDao.getPartNumberByBaseProductAndPsTypeList(psType , reportForm.getBaseProductId() ) );
                    }
                    else
                    {
                        request.setAttribute( "partNumberList", ProductDao.loadAllPartsForProcessTypeByPsType( psType ) );
                    }

                    request.setAttribute( "locationList",   VendorDAO.getVendorNamesByPsType(null, psType ) );
                }

                request.setAttribute( "processStepTypeList", loadProcessStepTypeList() );
                request.setAttribute( "baseProductList", ProductDao.loadChipBaseProducts(null) );

                actionForward = mapping.findForward( "yield" );
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
        }

        if( ( "engpull".equalsIgnoreCase( action ) ) || ( "scrap".equalsIgnoreCase( action ) ) )
        {

            partNumberList = FinishedGoodsDAO.loadAllFinishedGoodsWithoutBoardAndKits();
            mktgPartNumberSelectList = new ArrayList();
            FinishedGoods finishedGoods = null;

            for( int i = 0; i < partNumberList.size(); i++ )
            {
                finishedGoods = ( FinishedGoods ) partNumberList.get( i );
                mktgPartNumberSelectList.add( finishedGoods );
            }
            request.setAttribute( "partNumberList", mktgPartNumberSelectList );
        }

        if( "engpull".equalsIgnoreCase( action ) )
        {
            actionForward = mapping.findForward( "engpull" );
        }
        else if( "scrap".equalsIgnoreCase( action ) )
        {
            actionForward = mapping.findForward( "scrap" );
        }
        else if( "yieldSummary".equalsIgnoreCase( action ) )
        {
            if( ( reportForm.getProcessStep() == null ) || "0".equalsIgnoreCase(reportForm.getProcessStep() ) )
            {
                request.setAttribute( "partNumberList", new ArrayList() );
                request.setAttribute( "locationList",    VendorDAO.getVendorNamesByPsType(null, "ALL") );
            }
            else
            {
                psType = reportForm.getProcessStep();

                if ( reportForm.getBaseProductId() > 0  )
                {
                    request.setAttribute( "partNumberList", ProductDao.getPartNumberByBaseProductAndPsTypeList(psType , reportForm.getBaseProductId() ) );
                }
                else
                {
                    request.setAttribute( "partNumberList", ProductDao.loadAllPartsForProcessTypeByPsType( psType ) );
                }

                request.setAttribute( "locationList",   VendorDAO.getVendorNamesByPsType(null, psType ) );
            }

            request.setAttribute( "processList", loadSummaryReportProcessList() );
            request.setAttribute( "baseProductList", ProductDao.loadChipBaseProducts(null) );

            actionForward = mapping.findForward( "yieldSummary" );
        }
        else if( "cumyieldReport".equalsIgnoreCase( action ) )
        {
            request.setAttribute( "baseProductList", ProductDao.loadChipBaseProducts( null ) );
            actionForward = mapping.findForward( "cumyieldReport" );
        }
        else if( "vendor".equalsIgnoreCase( action ) )
        {             
            ArrayList vendorTempList = VendorDAO.getAllVendors();
            ArrayList vendorList = new ArrayList();
            for( int i = 0; i < vendorTempList.size(); i++ )
            {
                Vendor vendor = ( Vendor ) vendorTempList.get( i );
                vendorList.add( new LabelValueBean( vendor.getVendorName(), vendor.getVendorName() ) );
            }
            request.setAttribute( "vendorList", vendorList );
            request.setAttribute( "productList", loadAllFabProducts() );
            actionForward = mapping.findForward( "vendor" );
        }
        if ( "xlsYieldReport".equalsIgnoreCase(action) || "xlsYieldSoftBinReport".equalsIgnoreCase(action) )
        {
            String reportType = request.getParameter( "prompt6" );
            String defaultPrompt = request.getParameter( "prompt7" );

            String counter= request.getParameter( "prompt8" );
            String vendorIds = request.getParameter( "prompt3" );

            Map<String,String> paramMap = new HashMap<String,String>();
            paramMap.put ( "reportType", reportType );
            paramMap.put ( "defaultPrompt", defaultPrompt );
            paramMap.put ( "counter", counter );
            paramMap.put ( "processStep", reportForm.getProcessStep() );
            paramMap.put ( "psId", reportForm.getPsId()+"" );
            paramMap.put ( "baseProductId", reportForm.getBaseProductId()+"" );
            paramMap.put ( "vendorName", vendorIds );
            paramMap.put ( "fromDate", reportForm.getFromDate() );
            paramMap.put ( "toDate", reportForm.getToDate() );
			if ( "xlsYieldSoftBinReport".equalsIgnoreCase(action) )
			{
				paramMap.put ( "xlsYieldSoftBinReport", "xlsYieldSoftBinReport" );
			}
			else
			{
				paramMap.put ( "xlsYieldSoftBinReport", "xlsYieldHardBinReport" );
			}
            
            //yieldList = EngineeringDAO.getYieldReportDetails( null, paramMap );

            workbook = EngineeringDAO.getYieldReportWorkbook( null, paramMap ); //to comply with the report scheduling job

            if ("SORT".equalsIgnoreCase(counter) )
            {
                //workbook =  DataDumpReportsHelper.getWorkbook( yieldList, "Sort History Report" );
                fileName = "SortHistoryReport"+"_"+ DateUtil.getTimeStamp() ;
            }
            else if ("SORTBIN".equalsIgnoreCase(counter) )
            {
                //workbook =  DataDumpReportsHelper.getWorkbook( yieldList, "Sort History Bin Report" );
                fileName = "SortHistoryBinReport"+"_"+ DateUtil.getTimeStamp() ;
            }
            else if ("Assembly".equalsIgnoreCase(counter) )
            {
                //workbook =  DataDumpReportsHelper.getWorkbook( yieldList, "Sort History Bin Report" );
                fileName = "AssemblyHistoryReport"+"_"+ DateUtil.getTimeStamp() ;
            }
            else
            {
                //workbook =  DataDumpReportsHelper.getWorkbook( yieldList, "Test History Report" );
                fileName = "TestHistoryReport"+"_"+ DateUtil.getTimeStamp() ;
            }
            
            ExcelUtils.generateExcelReport( workbook, fileName, response);
        }
        if ( "xlsYieldSummaryReport".equalsIgnoreCase(action) )
        {

            ArrayList yieldList = EngineeringDAO.getTestBinSummaryYiledReport( null, reportForm );

            if ("summary".equalsIgnoreCase(reportForm.getReportType()) )
            {
                workbook =  DataDumpReportsHelper.getWorkbook( yieldList, "Test Bin Summary Report", null,null,null );
                 fileName = "TestBinSummaryReport"+"_"+ DateUtil.getTimeStamp() ;
            }
            else if ("detail".equalsIgnoreCase(reportForm.getReportType()) )
            {
                workbook =  DataDumpReportsHelper.getWorkbook( yieldList, "Test Bin Detail Report", null,null,null );
                fileName = "TestBinDetailReport"+"_"+ DateUtil.getTimeStamp() ;
            }

            ExcelUtils.generateExcelReport( workbook, fileName, response);
        }
        if ( "sortYield100BinReport".equalsIgnoreCase(action) )
        {
            String reportType = request.getParameter( "prompt6" );
            String defaultPrompt = request.getParameter( "prompt7" );
            String vendorIds = request.getParameter( "prompt3" );
            String counter= request.getParameter( "prompt8" );

            Map paramMap = new HashMap();
            paramMap.put ( "reportType", reportType );
            paramMap.put ( "defaultPrompt", defaultPrompt );
            paramMap.put ( "counter", counter );
            paramMap.put ( "processStep", reportForm.getProcessStep() );
            paramMap.put ( "psId", reportForm.getPsId()+"" );
            paramMap.put ( "baseProductId", reportForm.getBaseProductId()+"" );
            paramMap.put ( "vendorName", vendorIds );
            paramMap.put ( "fromDate", reportForm.getFromDate() );
            paramMap.put ( "toDate", reportForm.getToDate() );

            String csvString = "";
            //yieldList = EngineeringDAO.getYieldReportDetails( null, paramMap );
            //workbook = EngineeringDAO.getYield100BinReportWorkbook( null, paramMap ); //to comply with the report scheduling job
            csvString = EngineeringDAO.getYield100BinReportCSV( null, paramMap ); //to comply with the report scheduling job

            fileName = "SortHistoryBinReport"+"_"+ DateUtil.getTimeStamp() +".csv";


            //ExcelUtils.generateExcelReport( workbook, fileName, response);
            ExcelUtils.generateCSVReport( csvString, fileName, response);
        }

        return actionForward;
    }

    public static ArrayList loadAllFabProducts() throws Exception
    {
        ArrayList partNumberList = null;
        ArrayList fabPartNumberList = new ArrayList();
        PartNumber partNumber = null;
        partNumberList = ProductDao.getPartNumber( "FAB" );
        for( int i = 0; i < partNumberList.size(); i++ )
        {
            partNumber = ( PartNumber ) partNumberList.get( i );
            fabPartNumberList.add( new LabelValueBean( partNumber.getPartNumber(), partNumber.getProcessStepId() ) );
        }
        return fabPartNumberList;
    }

    public static ArrayList<LabelValueBean> loadProcessStepTypeList() throws Exception
    {
        ArrayList<LabelValueBean> processStepList = new ArrayList<LabelValueBean>();

        //processStepList.add( new LabelValueBean ( "FAB" ,  "FAB" ) );
        processStepList.add( new LabelValueBean ( "SORT" , "SORT" ) );
        processStepList.add( new LabelValueBean ( "SORT-(Wafer Vs. Bin)", "SORTBIN" ) );
        processStepList.add( new LabelValueBean ( "Assembly" ,  "Assembly" ) );
        processStepList.add( new LabelValueBean ( "FT" ,  "FT" ) );
        
        return processStepList;
    }
    public static ArrayList<LabelValueBean> loadSummaryReportProcessList() throws Exception
    {
        ArrayList<LabelValueBean> processStepList = new ArrayList<LabelValueBean>();

        processStepList.add( new LabelValueBean ( "FT" ,  "FT" ) );

        return processStepList;
    }


}